using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;

namespace EntityKit.Runtime
{
    /// <summary>
    /// 双击事件组件，可挂载到GameObject上处理双击逻辑
    /// </summary>
    public class DoubleClickEventComponent : MonoBehaviour, IPointerClickHandler
    {
        [Tooltip("双击时间间隔（秒）")] public float clickInterval = 0.3f;

        public UnityEvent OnDoubleClick;
        public UnityEvent OnSingleClick;

        private float m_LastClickTime = -1f;
        private Coroutine m_ClickTimeoutCoroutine;
        private bool m_Destroyed = false;

        public void OnPointerClick(PointerEventData eventData)
        {
            // 如果组件已被销毁，不处理点击事件
            if (m_Destroyed) return;
            
            float currentTime = Time.time;

            if (m_LastClickTime >= 0 && (currentTime - m_LastClickTime) < clickInterval)
            {
                // 双击事件
                if (m_ClickTimeoutCoroutine != null)
                {
                    StopCoroutine(m_ClickTimeoutCoroutine);
                    m_ClickTimeoutCoroutine = null;
                }

                m_LastClickTime = -1f;
                OnDoubleClick?.Invoke();
            }
            else
            {
                // 单击事件
                m_LastClickTime = currentTime;

                if (m_ClickTimeoutCoroutine != null)
                {
                    StopCoroutine(m_ClickTimeoutCoroutine);
                }

                m_ClickTimeoutCoroutine = StartCoroutine(ClickTimeoutCoroutine());
                OnSingleClick?.Invoke();
            }
        }

        private IEnumerator ClickTimeoutCoroutine()
        {
            yield return new WaitForSeconds(clickInterval);
            m_ClickTimeoutCoroutine = null;
            // 只有在未被销毁时才重置时间
            if (!m_Destroyed)
            {
                m_LastClickTime = -1f;
            }
        }

        private void OnDisable()
        {
            if (m_ClickTimeoutCoroutine != null)
            {
                StopCoroutine(m_ClickTimeoutCoroutine);
                m_ClickTimeoutCoroutine = null;
            }

            m_LastClickTime = -1f;
        }
        
        /// <summary>
        /// 移除所有事件监听器
        /// </summary>
        public void RemoveAllListeners()
        {
            OnDoubleClick?.RemoveAllListeners();
            OnSingleClick?.RemoveAllListeners();
        }
        
        private void OnDestroy()
        {
            m_Destroyed = true;
            OnDisable();
            RemoveAllListeners();
        }
    }
}